package cn.iocoder.ny.module.mall.controller.admin.login;

import cn.hutool.core.lang.UUID;
import cn.iocoder.ny.module.mall.controller.admin.login.dto.WxLoginDTO;
import cn.iocoder.ny.module.mall.controller.admin.login.vo.WxRegisterVo;
import cn.iocoder.ny.module.mall.service.IMallLoginService;
import cn.iocoder.ny.module.mall.utils.CheckWXTokenUtils;
import cn.iocoder.ny.module.mall.utils.HttpClientUtils;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import com.alibaba.fastjson2.JSON;
import com.google.gson.JsonObject;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * @author luchunhong
 * @date 2024/10/18/ 15:14
 * @description:
 */

@RestController
@RequestMapping("login")
public class MallLoginController {


    @Autowired
    private IMallLoginService mallLoginService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Value("${wxgzh.appid}")
    private String appId;
    @Value("${wxgzh.secret}")
    private String secret;


//    手机端登录
    @PostMapping("wxLogin")
    @PermitAll
    public CommonResult<AuthLoginRespVO> wxLogin(@RequestBody WxLoginDTO wxLoginDTO) throws Exception {
        AuthLoginRespVO authLoginRespVO = mallLoginService.wxLogin(wxLoginDTO);
        return success(authLoginRespVO);
    }

    // 查询该用户是否设置过登录密码
    @PostMapping("checkPassword")
    @PermitAll
    public CommonResult<Boolean> checkPassword(Long userName) {
//        Boolean checkPhoneMessageCode = mallLoginService.checkPassword(userName);
        return success(null);
    }


    // 若微信获取手机号没有授权登录额度则用该登录
    @PostMapping("login")
    @PermitAll
    public CommonResult<AuthLoginRespVO> loginNormal(@RequestBody WxLoginDTO wxLoginDTO) {
        AuthLoginRespVO authLoginRespVO = null;
        try {
            authLoginRespVO = mallLoginService.loginNormal(wxLoginDTO);
        } catch (RuntimeException e) {
            return error(500,e.getMessage());
        } catch (Exception e) {
            return error(500,e.getMessage());
        }
        if (authLoginRespVO == null) {
            return CommonResult.error(500,"账号密码输入不正确");
        }
        return success(authLoginRespVO);
    }

    @GetMapping("wxGetTenatId")
    @PermitAll
    public CommonResult<Long> getTeantIdByAppid(String appId) {
        return success(mallLoginService.getTeantIdByAppid(appId));
    }

    @PostMapping("register")
    @PermitAll
    public CommonResult<String> register(@RequestBody WxRegisterVo wxRegisterVo) throws Exception {
        Boolean register = null;
        try {
            register = mallLoginService.register(wxRegisterVo);
        } catch (Exception e) {
            return error(500,e.getMessage());
        }

        if (register){
            return success("注册成功");
        }
        return error(500,"注册失败");
    }

    /**
     * 找回密码
     * @param wxRegisterVo
     * @return
     */
    @PostMapping("forget")
    @PermitAll
    public CommonResult<String> forget(@RequestBody WxRegisterVo wxRegisterVo) {
        Boolean forget = null;
        try {
            forget = mallLoginService.forget(wxRegisterVo);
        } catch (Exception e) {
            return error(500,e.getMessage());
        }
        if (forget){
            return success("修改成功");
        }
        return error(500,"修改失败");

    }




    /**
     *  微信公众号
     */
    /**
     * 接收微信公众号消息
     */
    @PostMapping("/callback")
    @PermitAll
    public String responseMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException, DocumentException {
        req.setCharacterEncoding("UTF-8");
        String respContent = mallLoginService.responseMsg(req);
        return respContent;
    }

    /**
     * 通过随机字符串获取tenantId(微信公众号)
     * @return
     */
    @GetMapping("/wxQrcodeGetTenantId")
    @PermitAll
    public CommonResult<Long> wxQrcodeGetTenantId(String sceneStr) {
        Long tenantId = mallLoginService.wxQrcodeGetTenantId(sceneStr);
        return success(tenantId);
    }

    /**
     * 微信公众号登录
     * @param sceneStr
     * @return
     */
    @GetMapping("/wxGZHLogin")
    @PermitAll
    public CommonResult<AuthLoginRespVO> wxGzhLogin(String sceneStr){
        AuthLoginRespVO authLoginRespVO = null;
        try {
            authLoginRespVO = mallLoginService.wxGzhLogin(sceneStr);
        } catch (Exception e) {
            return  error(500,e.getMessage());
        }
        return success(authLoginRespVO);
    }



    // 获取二维码
    @GetMapping("/getWxQRCodeParam")
    @PermitAll
    public CommonResult<Map<Object,Object>> getWxQRCodeParam() {
        String QRUrl = null;
        Map<Object, Object> map = new HashMap<>();
        try {
            // 第一步：发送请求获取access_token
            String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                    "&appid=" + appId +
                    "&secret=" + secret;
            String accessTokenRes = HttpClientUtils.doGet(getAccessTokenUrl);
            String accessToken = (String) JSON.parseObject(accessTokenRes).get("access_token"); // 获取到access_token
            String sceneStr = UUID.randomUUID().toString(); // 生成唯一的 scene_str

            // 第二步：通过access_token和一些参数发送post请求获取二维码Ticket
            String getTicketUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
            // 封装参数
            Map<String, Object> ticketInfo = new HashMap<>();
            ticketInfo.put("expire_seconds", 150000); // 二维码超时时间
            ticketInfo.put("action_name", "QR_STR_SCENE"); // 二维码类型
            Map<String, Object> scene = new HashMap<>();
            scene.put("scene_str", sceneStr);
            Map<String, Object> actionInfo = new HashMap<>();
            actionInfo.put("scene", scene);
            ticketInfo.put("action_info", actionInfo);

            String ticketJsonInfo = JSON.toJSON(ticketInfo).toString();
            String ticketRes = HttpClientUtils.doPostJson(getTicketUrl, ticketJsonInfo);
            String ticket = (String) JSON.parseObject(ticketRes).get("ticket");
            // 第三步：通过ticket获取二维码url
            String encodeTicket = URLEncoder.encode(ticket, "utf-8"); // 编码ticket
            String getQRUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + encodeTicket;
            QRUrl = getQRUrl; // 二维码url
            redisTemplate.opsForValue().set("wx_qr_code", sceneStr);
            map.put("qrUrl",QRUrl);
            map.put("eventKey",sceneStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.success(map);
    }

}
